﻿using System.Linq;
using AmorCanino.Common;
using AmorCanino.Exceptions;
using AmorCanino.Web.Models.Models;

namespace AmorCanino.Web.Models.Services
{
    public class UserService : IUserService
    {
        public bool isValidUser(string email, string password)
        {
            return getUserByCredentials(email, password) != null;
        }

        public AmorCanino.Web.Models.Authentication.User getUserByCredentials(string email, string password)
        {
            return (from u in new AmorCaninoDBDataContext().Users
                    where u.Email == email &&
                            u.Password == CriptoSecurity.HashPassword(password) &&
                            u.Visible
                    select new AmorCanino.Web.Models.Authentication.User()
                    {
                        Email = email,
                        Name = u.Name,
                        id = u.UserId,
                        Privileges = u.Privileges,
                        Visible = u.Visible
                    }).FirstOrDefault();
        }

        public AmorCanino.Web.Models.Authentication.User getUserById(int userId)
        {
            return (from u in new AmorCaninoDBDataContext().Users
                    where u.UserId == userId
                    select new AmorCanino.Web.Models.Authentication.User()
                    {
                        Email = u.Email,
                        Name = u.Name,
                        id = u.UserId,
                        Privileges = u.Privileges,
                        Visible = u.Visible,
                        UnreadedMessages = new MessagingService().GetUnreadedMessagesCount(userId)
                    }).FirstOrDefault();
        }

        public AmorCanino.Web.Models.Authentication.User CreateUser(UserRegistrationModel user)
        {
            var db = new AmorCaninoDBDataContext();
            var existingUser = db.Users.SingleOrDefault(u => u.Email == user.Email);

            if (existingUser != null) { throw new BusinessRuleException("El usuario no puede ser creado") { ExceptionType = BusinessRuleEnum.RepeatedData }; }

            var us = new User() {
                Email = user.Email,
                Name = user.Name,
                Password = CriptoSecurity.HashPassword(user.Password),
                Visible = true,
                Privileges = string.Empty
            };

            db.Users.InsertOnSubmit(us);
            db.SubmitChanges();

            return new Authentication.User() {
                id = us.UserId,
                Email = us.Email,
                Name = us.Name,
                Visible = true,
                Privileges = us.Privileges
            };
        }
    }
}